//
//  CacheViewController.m
//  iOSCodeLearning
//
//  Created by Ace on 2017/11/20.
//  Copyright © 2017年 Ace. All rights reserved.
//

#import "CacheViewController.h"
#import "AppModel.h"
@interface CacheViewController ()


/**
内存缓存
 */
@property(nonatomic,strong)  NSMutableDictionary *images;

/**
 操作缓存
 */
@property(nonatomic,strong) NSMutableDictionary  *operations;

/**
 数据源
 */
@property(nonatomic,strong) NSArray *apps;

/**
 存放图片下载任务的队列
 */
@property(nonatomic,strong)  NSOperationQueue *queue;


@end

@implementation CacheViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"多图片下载";
    self.view.backgroundColor = [UIColor whiteColor];
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.apps.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *ID = @"CacheTableViewCellID";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
    }
    AppModel *model = self.apps[indexPath.row];
    cell.textLabel.text = model.name;

    
    
    // 先去查看内存缓存中 该图片是否已经存在 ，如果存在直接展示 ，如果没有则去检测磁盘缓存
    // 如果有磁盘缓存，那么保存一份到内存，设置图片，否则直接下载
    UIImage *image  = [self.images objectForKey:model.download];
    if (image) {
//        NSLog(@"使用了内存缓存的图片");
        cell.imageView.image = image;
    }
    else{
        // 获得存储的文件夹路径
        NSString *cachesPath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).firstObject;
        // 获得图片的名称,不能包含“/”
        NSString *fileName = [model.download lastPathComponent];
        // 获得文件的全部路径
        NSString *fullPath = [cachesPath stringByAppendingPathComponent:fileName];
        // 检查磁盘缓存
        NSData *imageData = [NSData dataWithContentsOfFile:fullPath];
        if (imageData) {
            UIImage *image = [UIImage imageWithData:imageData];
            cell.imageView.image = image;
            [self.images setObject:image forKey:model.download];
        }
        else
        {
            //检测改图片是否正在下载 如果是则 误操作  否则 添加下载任务
            NSBlockOperation *download = [self.operations objectForKey:model.icon];
            if (download)
            {
                
            }
            else
            {
                // 设置占位图片
                cell.imageView.image = [UIImage imageNamed:@"111"];
                NSBlockOperation *download = [NSBlockOperation blockOperationWithBlock:^{
                    // 设置图标
                    NSURL *url = [NSURL URLWithString:model.download];
                    NSData *imageData = [NSData dataWithContentsOfURL:url];
                    UIImage *image = [UIImage imageWithData:imageData];
                    
                    // 容错
                    if (image == nil)
                    {
                        [self.operations removeObjectForKey:model.download];
                        return ;
                    }
                    //保存到内存缓存
                    [self.images setObject:image forKey:model.download];
                    //回到主线程
                    [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                        [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationRight];
                        NSLog(@"刷新第%ld行 ，%@",indexPath.row,model.download);
                    }];
                    // 写数据到沙盒
                    [imageData writeToFile:fullPath atomically:YES];
                    
                    // 移除图片的下载操作
                    [self.operations removeObjectForKey:model.download];
                }];
                
                //添加操作 到操作缓存中
                [self.operations setObject:download forKey:model.download];
                
                // 添加操作到队列中
                [self.queue addOperation:download];
            }
        }
    }
    return cell;

}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 100;
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    UIViewController *vc = self.presentingViewController;
    UIViewController *vc1 = self.presentedViewController;
    
}

-(NSArray*)apps{
    
    if (!_apps ) {
        NSArray *arrayDict = [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle]pathForResource:@"urls.plist" ofType:nil]];
        
        NSMutableArray *arrayModel = [NSMutableArray array];
        for (NSDictionary *dict in arrayDict) {
            [arrayModel addObject:[AppModel appWithDict:dict]];
        }
        _apps = arrayModel;
    }
    return _apps;
}

-(NSMutableDictionary*)images{
    
    if (!_images) {
        _images = [NSMutableDictionary dictionary];
    }
    return _images;
}

-(NSOperationQueue*)queue{
    
    if (!_queue ) {
        _queue = [[NSOperationQueue alloc] init];
        // 设置队列的最大并发数
        _queue.maxConcurrentOperationCount = 5;
    }
    return _queue;
}


-(NSMutableDictionary*)operations{
    
    if (!_operations ) {
        _operations = [NSMutableDictionary dictionary];
    }
    return _operations;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    //接收到内存警告以后 清除内存缓存
    [self.images removeAllObjects];
    // 取消队列中正在下载的操作
    [self.queue cancelAllOperations];
}

/*
 Document: 会备份，不允许将缓存文件放在此处
 Libray:
     Caches: 缓存文件
     Preferences:偏好设置，保存账号
 tmp:临时路径，（随时有可能会被删除）
 */


@end
